<template>
  <Form style="margin-bottom: 10px">
    <Row :gutter="25">
      <Col span="5">
        <Form.Item label="Host">
          <Select v-model:value="form.env" @change="inputEl.focus();">
            <Select.Option v-for="item of form.envs" :value="item.value">{{ item.name }}</Select.Option>
          </Select>
        </Form.Item>
      </Col>
      <Col span="14">
        <Form.Item label="ID | 流水号">
          <Input ref="inputEl" v-model:value="form.serialNumber" allowClear placeholder="请输入业务ID或者流水号" />
        </Form.Item>
      </Col>
      <Col span="5" class="btn-group" style="text-align: right">
        <Button @click="search" type="primary"><SearchOutlined /> 查询</Button>
        <Button type="default" :disabled="!workflow.common.ID" @click="onCopyResult"><CopyFilled /> 复制结果</Button>
      </Col>
    </Row>
  </Form>
  <template v-if="workflow.common.ID">
    <Card title="主数据信息(双击项复制值)" size="small">
      <template #extra>
        <span class="btn-group" style="text-align: right; margin-right: -15px">
          <Button type="primary" @click="getPageAccesses"><HistoryOutlined /> 页面访问</Button>
          <Button type="primary" danger @click="download"><DownloadOutlined /> PDF下载</Button>
          <Button type="primary" @click="getDoaConfigs"><SettingOutlined /> DOA配置</Button>
          <Button type="default" @click="getThirdApis"><FundViewOutlined /> 查看回调</Button>
          <Button type="primary" @click="getApiLogs"><FileTextOutlined /> 查看接口调用日志</Button>
        </span>
      </template>
      <bizform :data="workflow.common" :env="form.env" />
    </Card>

    <Card title="当前审批人" size="small">
      <Table size="small" bordered :pagination="false" :columns="columns.worklists" :data-source="workflow.worklists" :scroll="{ x: true }"></Table>
    </Card>

    <Card title="审批人列表" size="small">
      <Table size="small" bordered :pagination="false" :columns="columns.destinationUsers" :data-source="workflow.destinationUsers" :scroll="{ x: true }">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key == 'hold-on'">
            <p>{{ record.HoldStartDate }}</p>
            <p>{{ record.HoldComments }}</p>
          </template>
        </template>
      </Table>
    </Card>

    <Card title="审批日志" size="small">
      <Table :columns="columns.logs" :pagination="false" :data-source="workflow.logs" size="small" bordered :scroll="{ x: true }" />
    </Card>
  </template>

  <Modal title="页面访问记录" v-model:visible="showPageAccess" :footer="null" width="100%" wrap-class-name="full-modal">
    <Table :columns="columns.pageAccesses" :pagination="false" :data-source="workflow.pageAccesses" size="small" bordered :scroll="{ x: true }" />
  </Modal>

  <Modal title="三方接口调用" v-model:visible="showThirdApi" :footer="null" width="100%" wrap-class-name="full-modal">
    <table class="table">
      <tbody v-for="(api, index) of thirdApis">
        <tr>
          <th rowspan="8" style="width: 70px">{{ index + 1 }}</th>
          <th style="width: 130px">系统名称</th>
          <td>{{ api.SystemName }}({{ api.id }})</td>
        </tr>
        <tr>
          <th>接口</th>
          <td>{{ api.Method }} - {{ api.Url }}</td>
        </tr>
        <tr>
          <th style="height: auto">发送数据</th>
          <td style="height: auto">{{ api.PostData }}</td>
        </tr>
        <tr>
          <th>执行结果</th>
          <td>{{ api.Result }}</td>
        </tr>
        <tr>
          <th>执行次数</th>
          <td>{{ api.SendTimes }}</td>
        </tr>
        <tr>
          <th>开始时间</th>
          <td>{{ api.CreateTime }}</td>
        </tr>
        <tr>
          <th>最后发送时间</th>
          <td>{{ api.LastSendTime }}</td>
        </tr>
        <tr>
          <th>发送状态</th>
          <td>
            {{ api.SendStatus }}
            <Button @click="RedoCallApi(api.id)" v-if="api.SendStatus == 0 && api.SendTimes == 6" type="primary" shape="round"><RedoOutlined /> 重新发送 </Button>
          </td>
        </tr>
      </tbody>
    </table>
  </Modal>

  <Modal title="DOA配置详情" v-model:visible="showDoaConfig" :footer="null" width="100%" wrap-class-name="full-modal">
    <Table :rowKey="getRowKey" :expandFixed="true" :scroll="{ x: true }" :columns="columns.doaItems" :pagination="false" :data-source="workflow.doaItems" size="small" @resizeColumn="resizeColumn" bordered>
      <template #expandedRowRender="{ record }">
        <div class="details">
          <div>
            <label>允许附件</label> <span>{{ record.CanUploadAttachment }}</span>
          </div>
          <div>
            <label>当前节点回调</label> <span>{{ record.CurrentNodeCallBackApi }}</span>
          </div>
          <div>
            <label>三方可修改</label> <span>{{ record.IsThirdCanEdit ? '是' : '否' }}</span>
          </div>
          <div>
            <label>运行控制附件显示</label> <span>{{ record.IsCanOperControl ? '是' : '否' }}</span>
          </div>
          <div>
            <label>三方邮件节点</label> <span>{{ record.IsThirdEmailNode ? '是' : '否' }}</span>
          </div>
          <div>
            <label>角色名</label> <span>{{ record.Roles }}</span>
          </div>
        </div>
      </template>
    </Table>
  </Modal>

  <Modal title="接口访问记录" v-model:visible="showApiLogs" :footer="null" width="100%" wrap-class-name="full-modal">
    <Table :rowKey="getApiLogRowKey" :expandFixed="left" :columns="columns.apiLogs" :pagination="false" :data-source="workflow.apiLogs" size="small" bordered :scroll="{ x: 800 }">
      <template #expandedRowRender="{ record }">
        <div class="details block">
          <div @dblclick="copyText(record.RequestUrlPara)">
            <label>请求参数</label> <span>{{ record.RequestUrlPara }}</span>
          </div>
          <div @dblclick="copyText(record.RequestContent)">
            <label>请求体</label> <span>{{ record.RequestContent }}</span>
          </div>
          <div @dblclick="copyText(record.ResponseContent)">
            <label>响应结果</label> <span>{{ record.ResponseContent }}</span>
          </div>
        </div>
      </template>
    </Table>
  </Modal>
</template>
<script setup>
  import { h, ref, reactive, inject, onMounted } from 'vue';
  import { Card, Form, Row, Col, Input, Modal, Select, Button, Table } from 'ant-design-vue';
  import { CopyFilled, DownloadOutlined, SearchOutlined, SettingOutlined, FundViewOutlined, HistoryOutlined, RedoOutlined, FileTextOutlined } from '@ant-design/icons-vue';

  import bizform from '@/views/capitaland/components/BizFormCommon.vue';

  const $http = inject('$http');
  const $message = inject('$message');
  const $modal = inject('$modal');
  const $copyText = inject('$copyText');

  const inputEl = ref();
  const showPageAccess = ref(false);
  const showThirdApi = ref(false);
  const showDoaConfig = ref(false);
  const showApiLogs = ref(false);

  const thirdApis = ref([]);

  const form = reactive({
    env: 'prod',
    envs: [
      { name: '正式环境', value: 'prod' },
      { name: 'UAT&测试环境', value: 'uat' }
    ],
    serialNumber: ''
  });

  const workflow = reactive({
    common: {},
    worklists: [],
    pageAccesses: [],
    destinationUsers: [],
    logs: [],
    doaDetail: {},
    doaItems: [],
    apiLogs: []
  });

  const appSecret = 'AppID=F76D7D4B-7154-47D7-B7D7-51720075D2F4&AppSecret=A780C92E-F023-4537-9269-28DA61A85A28';

  const columns = {
    worklists: [
      { title: 'ID', dataIndex: 'ID', width: 100, ellipsis: true },
      { title: 'NodeId', dataIndex: 'NodeID', width: 100, ellipsis: true },
      { title: 'K2WorkflowSN', dataIndex: 'K2WorkflowSN', width: 160, ellipsis: true },
      { title: '审批人ID', dataIndex: 'ApprovalUserID', width: 160, ellipsis: true },
      {
        title: '审批人',
        ellipsis: true,
        customRender: ({ record }) => {
          return `${record.ApprovalUserDisplayNameCN}(${record.ApprovalUserDisplayNameEN})`;
        }
      }
    ],
    pageAccesses: [
      { title: '单据ID', dataIndex: 'BizFormId', width: 70, ellipsis: true },
      { title: '流水号', dataIndex: 'SerialNumber', width: 240, ellipsis: true },
      { title: '标题', dataIndex: 'Title', width: 210, ellipsis: true },
      { title: '流程名称', dataIndex: 'ProcessName', width: 100, ellipsis: true },
      { title: '项目名称', dataIndex: 'ProjectName', width: 150, ellipsis: true },
      { title: '部门名称', dataIndex: 'DepartmentName', width: 100, ellipsis: true },
      { title: '访问方式', dataIndex: 'AccessType', width: 70, ellipsis: true },
      { title: '加载开始时间', dataIndex: 'LoadedDateTime', width: 150, ellipsis: true },
      { title: '加载完成时间', dataIndex: 'CompletedDateTime', width: 150, ellipsis: true },
      {
        title: '共耗时',
        customRender: ({ record }) => {
          let begin = new Date(record.LoadedDateTime);
          let end = new Date(record.CompletedDateTime);

          return (end.getTime() - begin.getTime()) / 1000 + '秒';
        },
        width: 100,
        ellipsis: true
      },
      { title: '次数', dataIndex: 'RecordMark', width: 50, ellipsis: true }
    ],
    doaItems: reactive([
      { title: 'DOA名称', dataIndex: 'DOAColumnName', width: 160, resizable: true, ellipsis: true },
      { title: '节点ID', dataIndex: 'NodeSeq', width: 80, ellipsis: true },
      { title: 'Action', dataIndex: 'Action', width: 80, ellipsis: true },
      { title: 'K2节点名', dataIndex: 'K2ActivityName', width: 120, ellipsis: true },
      { title: '执行前置表达式', dataIndex: 'PreExcuteExpression', minWidth: 100, width: 200, resizable: true, ellipsis: true },
      { title: '角色表达式', dataIndex: 'RoleExpression', width: 160, resizable: true, ellipsis: true }
    ]),
    destinationUsers: [
      { title: 'ID', dataIndex: 'ID', width: 100 },
      { title: 'NodeId', dataIndex: 'NodeID', width: 100 },
      { title: 'RoleTypeID', dataIndex: 'RoleTypeID', width: 120 },
      { title: 'UserID', dataIndex: 'UserID', width: 140 },
      {
        title: '用户信息',
        width: 200,
        ellipsis: true,
        customRender: ({ record }) => {
          let item = record;

          return h('span', `${item.UserDisplayNameCN}(${item.UserDisplayNameEN})`);
        }
      },
      {
        title: 'UserID(实际)',
        width: 140,
        ellipsis: true,
        customRender: ({ record }) => {
          return h('span', `${record.OperatorUserID || record.UserID}`);
        }
      },
      {
        title: '用户信息(实际)',
        width: 200,
        ellipsis: true,
        customRender: ({ record }) => {
          let item = record;

          return h('span', `${item.OperatorDisplayNameCN || item.UserDisplayNameCN}(${item.OperatorDisplayNameEN || item.UserDisplayNameEN})`);
        }
      },
      {
        title: '审批状态',
        width: 100,
        ellipsis: true,
        customRender: ({ record }) => {
          return h('span', `${record.IsApproved ? '已审批' : '未审批'}`);
        }
      },
      {
        title: '创建时间',
        width: 150,
        ellipsis: true,
        customRender: ({ record }) => {
          return h('span', record.CreatedOn);
        }
      },
      { title: '暂缓', width: 200, key: 'hold-on', ellipsis: true }
    ],
    logs: [
      {
        title: '审核人',
        width: 280,
        ellipsis: true,
        customRender: ({ record }) => {
          return `${record.ApprovalUserDisplayNameCN}(${record.ApproverID})`;
        }
      },
      {
        title: '实际审核人',
        width: 280,
        ellipsis: true,
        customRender: ({ record }) => {
          return h('span', `${record.OriginalityUserDisplayNameCN}(${record.OriginalityUserID})`);
        }
      },
      {
        title: '审批日期',
        width: 150,
        ellipsis: true,
        customRender: ({ record }) => {
          return h('span', record.AuditingDate);
        }
      },
      { title: '动作', dataIndex: 'ActionName', width: 120, ellipsis: true },
      { title: '审批意见', dataIndex: 'Comment', ellipsis: true }
    ],
    apiLogs: [
      { title: 'ID', dataIndex: 'ID', width: 60, ellipsis: true },
      { title: '接口地址', dataIndex: 'APIUrl', width: 420, ellipsis: true },
      { title: '控制器', dataIndex: 'Controller', width: 120, ellipsis: true },
      { title: '执行方法', dataIndex: 'Action', width: 200, ellipsis: true },
      { title: '开始时间', dataIndex: 'CreatedOn', width: 120, ellipsis: true },
      { title: '响应时间', dataIndex: 'ResponseTime', width: 120, ellipsis: true }
    ]
  };

  function getRowKey(record) {
    return record.NodeSeq;
  }

  function getApiLogRowKey(record) {
    return record.ID;
  }

  function resizeColumn(w, col) {
    col.width = w;
  }

  function search() {
    if (!form.serialNumber) {
      $message.warning('请输入ID | 流水号');

      return;
    }

    $http.get(`/api/iworkflow/${form.env}/workflow/details?serialNumber=${form.serialNumber}`).then(res => {
      if (res.common == undefined) {
        $message.warning('没有找到符合条件的流程详情！');
      }

      workflow.common = res.common || {};
      workflow.worklists = reactive(res.worklists || []);
      workflow.destinationUsers = reactive(res.destinationUsers || []);
      workflow.logs = reactive(res.logs || []);
      workflow.pageAccesses = [];
      workflow.doaDetail = {};
      workflow.doaItems = [];
      workflow.apiLogs = [];
    });
  }

  function onCopyResult() {
    $copyText(JSON.stringify(workflow, null, 2)).then(() => {
      $message.success('结果已复制！');
    });
  }

  function copyText(text) {
    text = (text || '').indexOf('=') == 0 ? text.substr(1) : text;

    $copyText(text).then(() => {
      $message.success('内容已复制！');
    });
  }

  function getPageAccesses() {
    $http.post(`/api/iworkflow/${form.env}/workflow/pageAccess`, [workflow.common.SerialNumber]).then(rs => {
      showPageAccess.value = true;
      workflow.pageAccesses = rs.datas;
    });
  }

  function getDoaConfigs() {
    $http.get(`/api/iworkflow/${form.env}/workflow/doaitems/${workflow.common.DOAItemID}`).then(res => {
      showDoaConfig.value = true;

      workflow.doaDetail = res.detail;
      workflow.doaItems = res.items;
    });
  }

  function getApiLogs() {
    let data = {
      ProcessGroupName: workflow.common.ProcessGroupName,
      appId: workflow.common.AppID,
      content: workflow.common.Title
    };

    $http.post(`/api/iworkflow/${form.env}/workflow/apilog`, data).then(rs => {
      showApiLogs.value = true;
      workflow.apiLogs = rs.datas;
    });
  }

  function getThirdApis() {
    $http.get(`/api/iworkflow/log/${form.env}/thirdparty/${workflow.common.ID}`).then(rs => {
      showThirdApi.value = true;
      thirdApis.value = rs.datas;
    });
  }

  function RedoCallApi(apiId) {
    $modal.confirm({
      title: '提示',
      content: '是否确定重新开始回调？',
      onOk: () => {
        $http.post(`/api/iworkflow/log/${form.env}/redoCall/${apiId}`).then(res => {
          getThirdApis();
        });
      }
    });
  }

  function download() {
    let webHost = 'https://nwf.capitaland.com.cn';
    let host = `https://nwf.capitaland.com.cn/wfapi`;

    if (form.env != 'prod') {
      webHost = 'https://nwfuat.capitaland.com.cn';
      host = `http://iworkflowuat.dc.capitaland.com/wfapi7001`;
    }

    let duration = 10;
    let processGroupName = (workflow.common.ProcessGroupName || '').toLowerCase();

    if (processGroupName.indexOf('leo') != -1) {
      duration = 50;
      webHost += `/Process/MyWorkFlow/AopForm?ProcessID=${workflow.common.ProcessID}|BizFormId=${workflow.common.ID}|UserId=${workflow.common.ApplicantUserID}`;
    } else if (processGroupName.indexOf('clsa3.0') != -1) {
      webHost += `/Seal/Application/FormDetail?ProcessID=${workflow.common.ProcessID}|BizFormId=${workflow.common.ID}|UserId=${workflow.common.ApplicantUserID}`;
    } else if (processGroupName.indexOf('clsa') != -1) {
      webHost += `/Process/UseBySeal/SealByBorrowDetail?ProcessID=${workflow.common.ProcessID}|BizFormId=${workflow.common.ID}|UserId=${workflow.common.ApplicantUserID}`;
    } else {
      webHost += `/Process/MyWorkFlow/AopFormCommon?ProcessID=${workflow.common.ProcessID}|BizFormId=${workflow.common.ID}|UserId=${workflow.common.ApplicantUserID}`;
    }

    $message.loading({ content: 'PDF正在生成中，请稍后...', duration: duration, key: 'pdfCreate' });

    window.open(`${host}/api/Pdf/GenerateForUrl?${appSecret}&fileName=表单_${workflow.common.SerialNumber}&url=${webHost}`, '_self');
  }

  onMounted(() => {
    inputEl.value.focus();
  });
</script>

<style lang="less">
  .workflow-detail {
    margin-top: 10px;

    > p {
      background: #fff;
      font-size: 16px;
      font-weight: bold;
      padding: 9px 15px;
      border: 1px solid #d8d8d8;
      border-radius: 5px 5px 0 0;
      margin-bottom: -1px;
      display: inline-block;
      vertical-align: middle;
      line-height: 24px;
      height: 42px;
      width: 100%;

      > .ivu-btn-group {
        top: -5px;
        float: right;
      }
    }
  }

  .table {
    height: auto;

    th {
      height: auto;
      text-align: right;
      background: transparent;
      border-bottom: 1px solid #e8eaec;

      &:after {
        content: '：';
      }

      &[rowspan] {
        text-align: center;
        padding-right: 0;
        border-right: 1px solid #e8eaec;

        &:after {
          content: '';
        }
      }
    }

    > tbody {
      margin-bottom: 10px;

      td {
        height: auto;
        padding: 8px 0 8px 5px;
        line-height: 16px;
        border: 1px solid #e8eaec;
      }
    }
  }
</style>
